package cn.ming.wfchat.kit.contact.pick;

import android.app.Activity;
import android.content.Intent;
import android.view.View;

import java.util.ArrayList;
import java.util.List;

import cn.ming.wfchat.kit.channel.ChannelListActivity;
import cn.ming.wfchat.kit.contact.BaseUserListFragment;
import cn.ming.wfchat.kit.contact.model.FriendRequestValue;
import cn.ming.wfchat.kit.contact.model.UIUserInfo;
import cn.ming.wfchat.kit.contact.newfriend.FriendRequestListActivity;
import cn.ming.wfchat.kit.group.GroupListActivity;
import cn.ming.wfchat.kit.utils.Tools;

public class ChooseUserFragment extends BaseUserListFragment {
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (userListAdapter != null && isVisibleToUser) {
            contactViewModel.reloadContact();
            contactViewModel.reloadFriendRequestStatus();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        contactViewModel.reloadContact();
        contactViewModel.reloadFriendRequestStatus();
    }

    @Override
    protected void afterViews(View view) {
        super.afterViews(view);
        contactViewModel.contactListLiveData().observe(this, userInfos -> {
            showContent();
            List<UIUserInfo> uiUserInfoList = new ArrayList<>();
            for (UIUserInfo info : userInfos) {
                if (Tools.isInteger(info.getUserInfo().uid)) {
                    uiUserInfoList.add(info);
                }
            }
            userListAdapter.setUsers(uiUserInfoList);
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }


    @Override
    public void onUserClick(UIUserInfo userInfo) {
        Intent intent = new Intent();
        intent.putExtra("userid", userInfo.getUserInfo().uid);
        getActivity().setResult(Activity.RESULT_OK, intent);
        getActivity().finish();
    }

    @Override
    public void onHeaderClick(int index) {
        switch (index) {
            case 0:
                showFriendRequest();
                break;
            case 1:
                showGroupList();
                break;
            case 2:
                showChannelList();
                break;
            default:
                break;
        }
    }

    private void showFriendRequest() {
        FriendRequestValue value = new FriendRequestValue(0);
        userListAdapter.updateHeader(0, value);

        contactViewModel.clearUnreadFriendRequestStatus();
        Intent intent = new Intent(getActivity(), FriendRequestListActivity.class);
        startActivity(intent);
    }

    private void showGroupList() {
        Intent intent = new Intent(getActivity(), GroupListActivity.class);
        startActivity(intent);
    }

    private void showChannelList() {
        Intent intent = new Intent(getActivity(), ChannelListActivity.class);
        startActivity(intent);
    }
}
